package cn.micai.base.io;

import java.io.File;
import java.io.FilenameFilter;

/**
 * 描述：How to get all files with certain extension in a folder in java
 * <p>
 *
 * @author: 赵新国
 * @date: 2018/6/7 11:36
 */
public class GetAllFilesWithCertainExtMain {

    public static void main(String [] args) {

        GetAllFilesWithCertainExtMain getAllFilesWithCertainExtMain = new GetAllFilesWithCertainExtMain();

        System.out.println("Finding .pdf files in the folder D://BaiduNetdiskDownload");
        System.out.println("-----------------");

        // Read the file
        File folder = new File("D://BaiduNetdiskDownload");
        getAllFilesWithCertainExtMain.getAllFilesWithCertainExtension(folder, "pdf");

        System.out.println("-----------------");
    }

    private void getAllFilesWithCertainExtension(File folder, String filterExt) {
        MyExtFilter extFilter = new MyExtFilter(filterExt);
        if (!folder.isDirectory()) {
            System.out.println("Not a folder");
        } else {
            // list out all the file name and filter by the extension
            String[] list = folder.list(extFilter);
            if (list.length == 0) {
                System.out.println("no files end with: " + filterExt);
                return;
            }
            for (int i=0; i<list.length; i++) {
                System.out.println("File: " + list[i]);
            }
        }
    }

    // inner class, generic extension filter
    public class MyExtFilter implements FilenameFilter {
        private String ext;
        public MyExtFilter(String ext) {
            this.ext = ext;
        }
        @Override
        public boolean accept(File dir, String name) {
            return (name.endsWith(ext));
        }
    }

}
